lobsterh5.main({
    data: {
        backUrl: '', //回调地址 
        code: '', //微信网页授权成功回调参数:code作为换取access_token的票据，每次用户授权带上的code将不一样，code只能使用一次，5分钟未被使用自动过期
        state: '', //微信网页授权成功回调参数:重定向后会带上state参数，开发者可以填写a-zA-Z0-9的参数值，最多128字节
        openid: '',
        wxprepay: {},
        payOrderNo: '',
        ttl: 30,
        orderInfo: {},
        disabledbtn: false,
        downtime: "00:00"
    },
    pageload() {
        this.data.payOrderNo = lobsterh5.GetUrlParam("payOrderNo");
        this.data.backUrl = lobsterh5.GetUrlParam("callback");
        this.data.code = lobsterh5.GetUrlParam("code");
        this.data.openid = lobsterh5.GetUrlParam("openid");
        // alert('orderno:'+this.data.payOrderNo);
        // alert('code:'+this.data.code);
        // alert('openid:'+this.data.openid);
        $('#debug').append('<br/>orderno:' + this.data.payOrderNo);
        $('#debug').append('<br/>code:' + this.data.code)
        // $('#debug').append('<br/>openid:'+this.data.openid)
        //微信授权成功回调
        if (this.data.openid) {

            this.getalldata();
        } else {
            if (this.data.code) {
                this.authorizeCallback();
            } else {
                this.getAuthorizeUrl().then(res => {
                    location.href = res.data.url;
                }).catch(res => {
                    $.toast(res.msg, "text");
                })
            }
        }
        this.initevent();
    },
    initevent() {
        var self = this;
        $("#pay").click(function () {
            if (self.data.disabledbtn) {
                return;
            }
            if (!self.data.payOrderNo) {
                $.toast('订单号不正确', 'text');
            }
            $.showLoading();
            var payType = $("[name='radio1']:checked").val();
            lobsterh5.POSTAPI("tsfront.unifiedorder", {
                orderNo: self.data.payOrderNo,
                openid: self.data.openid,
                payType: payType
            }).then(res => {
                if (payType == 1) {
                    $.hideLoading();
                    // alert(JSON.stringify(res));
                    $('#debug').append('<br/>wxprepay:' + JSON.stringify(res.wxprepay));
                    self.data.wxprepay = res.wxprepay;
                    self.onBridgeReady();
                } else if (payType == 2) {

                } else if (payType == 3) {
                    $.showLoading("正在查询订单结果");
                    self.getOrderState().then(res => {
                        location.href = "success.html?orderNo=" + self.data.orderInfo.OrderNo;
                    }).catch(res => {
                        $.toast(res.msg || res, 'forbidden');
                        location.href = "fail.html?orderNo=" + self.data.orderInfo.OrderNo;
                    })
                }
            }).catch(res => {
                $.hideLoading();
                $.toast(res.msg || res, 'forbidden');
            });
        });
    },

    //获取微信授权跳转地址
    getAuthorizeUrl: function () {
        var self = this;
        return new Promise((resolve, reject) => {
            $.ajax({
                type: "get",
                url: "/admin/v1/clogin/getauthorizeurl?redirectUrl=" + location.href,
                success: function (res) {
                    if (res.code == 0) {
                        resolve(res);
                    } else {
                        reject(res);
                    }
                },
                error: function (xhr) {
                    reject(res);
                },
            });
        })
    },
    //微信授权成功回调
    authorizeCallback: function () {
        $.showLoading();
        var self = this;
        self.getWxUserInfo().then(res => {
            // $.hideLoading();
            let user = res.data.userinfo;
            $('#debug').append('<br/>openid:' + JSON.stringify(user.openid));
            self.data.openid = user.openid;
            self.getalldata();
        }).catch(res => {
            $.hideLoading();
            $.toast(res.msg, "text");
        })
    },

    //获取微信用户信息
    getWxUserInfo: function () {
        var self = this;
        return new Promise((resolve, reject) => {
            $.ajax({
                type: "get",
                url: "/admin/v1/clogin/getwxuserinfo?code=" + self.data.code,
                success: function (res) {
                    if (res.code == 0) {
                        resolve(res);
                    } else {
                        reject(res);
                    }
                },
                error: function (xhr) {
                    reject(res);
                },
            });
        })
    },
    //获取订单状态
    getOrderState: function () {
        var self = this;
        return new Promise((resolve, reject) => {
            //查询是否支付成功，成功了则跳转
            var number = 0;
            var d = setInterval(() => {
                number++;
                if (number >= 6) {
                    clearInterval(d);
                    $.hideLoading();
                    reject({
                        code: 1,
                        msg: "订单查询失败，请稍后重试!"
                    });
                }
                // alert(self.data.payOrderNo);
                lobsterh5.GETAPI('tsfront.getorderstate', {
                    orderNo: self.data.payOrderNo
                }).then(res => {
                    // alert(JSON.stringify(res));
                    if (res.payState == 2) {
                        clearInterval(d);
                        $.hideLoading();
                        resolve({
                            code: 0,
                            msg: "支付成功"
                        })
                    } else if (res.payState == 3) {
                        clearInterval(d);
                        $.hideLoading();
                        reject({
                            code: 1,
                            msg: "操作失败，已退款"
                        });
                    }
                }).catch(res => {
                    //alert(JSON.stringify(res));
                    reject({
                        code: 1,
                        msg: res.msg
                    })
                })
            }, 2000)
        })
    },
    getalldata() {
        var self = this;
        Promise.all([self.getorder(), self.getpaytypelist(), self.getaccountInfo()]).then(res => {
            $.hideLoading();
            self.data.orderInfo = res[0].data;
            var paytypelist = res[1].data;
            var account = res[2].account;


            $("#body1").text(self.data.orderInfo.Body);
            $("#price").text(self.data.orderInfo.TotalFee);

            self.downTime();
            // alert(JSON.stringify(paytypelist));
            // alert(JSON.stringify(res[2]));
            // paytypelist.forEach(item => {
            //     if (item.PayType == 3)
            //         item.Balance = parseFloat((account.Balance || 0)).toFixed(2);
            //     else
            //         item.Balance = "";
            // });
            var html = template("paytypelisttemp", { list: paytypelist, orderInfo: self.data.orderInfo });
            $("#paytypelist").html(html);
        }).catch(res => {
            $.hideLoading();
            $.toast(res.msg || res, 'forbidden');
        })
    },
    getorder: function () {
        var self = this;
        return new Promise((resolve, reject) => {
            lobsterh5.GETAPI("tsfront.getorder", {
                orderNo: self.data.payOrderNo,
            }).then(res => {
                // alert(res);
                resolve(res);
            }).catch(res => {
                reject(res);
            });
        })
    },
    getpaytypelist: function () {
        var self = this;
        return new Promise((resolve, reject) => {
            lobsterh5.GETAPI("tsfront.getpaytypelist", {
                orderNo: self.data.payOrderNo
            }).then(res => {
                resolve(res);
            }).catch(res => {
                reject(res);
            });
        })
    },
    getaccountInfo() {
        return new Promise((resolve, reject) => {
            // lobsterh5.CALLOUTSERVICE("wallet.wallet.getaccountInfo", {
            //     userId: localStorage.getItem("userId")
            // }).then(res => {
            //     resolve(res);
            // }).catch(res => {
            //     reject(res);
            // });

            resolve({ account: "" });
        })
    },
    /**倒计时 */
    downTime: function () {
        if (!this.data.orderInfo.OrderDate) return;
        var datestring = this.data.orderInfo.OrderDate.replace(/-/g, '/').substring(0, 19);
        var finishTime = Date.parse(new Date(datestring)) / 1000 +
            this.data.ttl * 60;
        var interval = setInterval(() => {
            let diff = (finishTime - Date.parse(new Date()) / 1000);
            if (diff < 0) {
                if (interval) {
                    clearInterval(interval);
                    this.data.disabledbtn = true;
                    $("#pay").removeClass("weui-btn_primary").addClass("weui-btn_disabled").addClass("weui-btn_default");
                }
            } else {
                let dateData = {
                    years: 0,
                    days: 0,
                    hours: 0,
                    min: 0,
                    sec: 0,
                }
                if (diff >= (365.25 * 86400)) {
                    dateData.years = Math.floor(diff / (365.25 * 86400))
                    diff -= dateData.years * 365.25 * 86400
                }
                if (diff >= 86400) {
                    dateData.days = Math.floor(diff / 86400)
                    diff -= dateData.days * 86400
                }
                if (diff >= 3600) {
                    dateData.hours = Math.floor(diff / 3600)
                    diff -= dateData.hours * 3600
                }
                if (diff >= 60) {
                    dateData.min = Math.floor(diff / 60)
                    diff -= dateData.min * 60
                }
                dateData.sec = Math.floor(diff);
                if (dateData.min < 10) dateData.min = "0" + dateData.min;
                if (dateData.sec < 10) dateData.sec = "0" + dateData.sec;
                this.data.downtime = dateData.min + ":" + dateData.sec;
                $("#time").text(this.data.downtime);
            }
        }, 1000)
    },
    onBridgeReady: function () {
        var self = this;
        // alert(JSON.stringify(self.data.wxprepay));
        if (typeof WeixinJSBridge == "undefined") {
            if (document.addEventListener) {
                document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady, false);
            } else if (document.attachEvent) {
                document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady);
                document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady);
            }
        } else {
            WeixinJSBridge.invoke(
                'getBrandWCPayRequest', {
                "appId": self.data.wxprepay.appId,     //公众号ID，由商户传入     
                "timeStamp": self.data.wxprepay.timeStamp,         //时间戳，自1970年以来的秒数     
                "nonceStr": self.data.wxprepay.nonceStr, //随机串     
                "package": self.data.wxprepay.package,//"prepay_id=u802345jgfjsdfgsdg888",
                "signType": self.data.wxprepay.signType,         //微信签名方式：     
                "paySign": self.data.wxprepay.paySign //微信签名 
            },
                function (res) {
                    if (res.err_msg == "get_brand_wcpay_request:ok") {
                        // 使用以上方式判断前端返回,微信团队郑重提示：
                        //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                        // alert('success');
                        // location.href="success.html";
                        $.showLoading("正在查询订单结果");
                        self.getOrderState().then(res => {
                            location.href = "success.html?orderNo=" + self.data.orderInfo.OrderNo;
                        }).catch(res => {
                            location.href = "fail.html?orderNo=" + self.data.orderInfo.OrderNo;
                        })
                    } else if ("get_brand_wcpay_request:cancel") {
                        $.toast("支付取消", "text");
                    } else {
                        // alert('fail');
                        location.href = "fail.html";
                    }
                });
        }
    }
})